package com.one.rope.mvp.web.common.auth;

import com.one.rope.mvp.basecore.util.StringUtils;
import com.one.rope.mvp.web.common.jwt.CookieUtils;
import com.one.rope.mvp.web.common.jwt.JwtUtil;
import com.one.rope.mvp.web.common.jwt.PayloadBean;
import com.one.rope.mvp.web.common.redis.AuthRedisOperator;
import com.one.rope.mvp.web.config.GlobalConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Weijian.liu
 * @desc 管理后台用户登录工具类
 * @date 2018/12/12
 */
@Slf4j
public class AdminUserLoginUtil {

  private static final ThreadLocal<AdminUserInfo> context = new ThreadLocal<AdminUserInfo>();

  private AdminUserLoginUtil() {
  }

  public static AdminUserInfo getUserInfo() {
    return context.get();
  }

  /**
   * 设置会话级别的session元素值
   */
  public static void initThreadContext(AdminUserInfo userInfo) {
    context.set(userInfo);
  }

  /**
   * 删除该线程本地当前线程的值变量
   */
  public static void clear() {
    context.remove();
  }

  /**
   * 获取Token
   */
  public static String getToken(HttpServletRequest request) {
    String token = request.getHeader(GlobalConfig.TOKEN_NAME);
    if (StringUtils.isNullOrEmpty(token)) {
      Cookie cookie = CookieUtils.getCookie(GlobalConfig.TOKEN_NAME, request);
      if (cookie != null) {
        token = cookie.getValue();
      }
    }
    return token;
  }

  /**
   * Token认证
   */
  public static PayloadBean auth(HttpServletRequest request) {
    String token = getToken(request);
    return auth(token);
  }

  /**
   * Token认证
   */
  public static PayloadBean auth(String token) {
    if (StringUtils.isNullOrEmpty(token)) {
      return null;
    }
    PayloadBean payload = JwtUtil.validToken(token);
    return payload;
  }

  /**
   * 更新缓存用户信息
   */
  public static AdminUserInfo updateAdminUserLoginInfo(String token, AdminUserInfo userInfo) throws Exception{
    String saveRes = AuthRedisOperator.saveAdminUserLoginToken(token, userInfo);
    if (null == saveRes) {
      return null;
    }
    return userInfo;
  }
}
